const { add, find, remove } = require('../model/position');
const fs = require('fs');
const path = require('path');

const positionController = {
    add: async({ req, res, router }) => {
        req.body.companyLogo = req.fileName;
        const flag = await add({...req.body });
        let data = null;
        if (flag) {
            data = { rat: flag, msg: '职位发布成功！' };
            // router.go('http://localhost:8000/interface/position');
        } else {
            data = { rat: flag, msg: '职位信息重复，发布失败！' };
        }
        res.render('positionAdd', {
            data: JSON.stringify(data)
        });
    },
    find: async({ req, res }) => {
        let result = await find().then(res => res);
        res.render('positionFind', {
            data: JSON.stringify(result)
        });
    },
    remove: async({ req, res }) => {
        let { id, companyLogo } = req.body;
        let flag = await remove({ id, companyLogo });
        let data;
        if (flag) {
            data = { rat: flag, msg: '删除成功' };
            fs.unlink(path.join(__dirname, '../public/upload/' + companyLogo), (err, res) => {
                console.log('本地图片已删除成功！');
                return;
            });
        } else {
            data = { rat: flag, msg: '删除失败' };
        }
        res.render('positionRemove', {
            data: JSON.stringify(data)
        });
    }
};

module.exports = positionController;